//
//  GamePlayer.m
//  Galaxy
//
//  Created by antl on 1/28/13.
//  Copyright (c) 2013 __MyCompanyName__. All rights reserved.
//

#import "GamePlayer.h"
#import "SimpleAudioEngine.h"
#import "MenuScene.h"
static CGPoint VITRI_ENEMY[]={
    {40,400},{90,400},{140,400},{190,400},{240,400},{290,400},/// dong 1
    {65,350},{115,350},{165,350},{215,350},{265,350},           /// dong 2
    {40,300},{90,300},{140,300},{190,300},{240,300},{290,300},  ///dong 3
    
};
static ENEMY_TYPE TYPE_ENEMY_ARRANGE[]={
    
    eType3,eType3,eType3,eType3,eType3,eType3,
    eType2,eType2,eType2,eType2,eType2,    
    eType1,eType1,eType1,eType1,eType1,eType1,
};
@implementation GamePlayer
-(id) init
{
	if(self==[super init])
	{
        typeBullet=NOMARL_BULLET;
        enableShooting=TRUE;
        self.isTouchEnabled = YES;
        self.isAccelerometerEnabled = YES; 
        [self initBackground];       
        [[UIAccelerometer sharedAccelerometer] setUpdateInterval:1/60];
        [self schedule:@selector(update:) interval:kEnemyMoveSpeed];     
        [self initBackground];
        [self setupInit];
        [self initPlayer];
        [self initEnemy];
        [self schedule:@selector(actionUpdate:) interval:1/60];
        
         CCMenuItemFont* btBack=[CCMenuItemFont itemWithString:@"Back"  target:self selector:@selector(back)];
         btBack.position=ccp(-120,220);
         CCMenu * iMenu=[CCMenu menuWithItems:btBack,nil];
        [self addChild:iMenu];
    }
    return self;
}
-(void)back
{
    [self changePageWithScene:[MenuScene node] type:FlipX];
}
-(void)dealloc
{
    [super dealloc];
    SAFE_RELEASE(listEnemy);
    SAFE_RELEASE(listBullet);
}
-(void)setupInit{   
    listEnemy=[[NSMutableArray alloc] init];
    listBullet = [[NSMutableArray alloc] init];
}
#pragma mark - INIT-
-(void)initBackground
{    /// ADD BACKGROUND GAME
    [self DrawImageSpritebyLayer:self andFileName:@"bg.png" atPosition:ccp(0,0) withZ:0 andScale:0 AnchorPoint:ccp(0,0)];
}
-(void)initPlayer
{
    /// init Enemy
    mySHIP=[self addImageAnimationByClass:[SHIP class] withZ:10];
    mySHIP.position=ccp(100,50);
    id Action1 = [mySHIP createAnimation];
    [mySHIP runAction:Action1]; 
}
-(void)initEnemy
{
    for (int index=0; index<NumberEnemy; index++) {
        Enemy *en=[[Enemy alloc] initWithType:TYPE_ENEMY_ARRANGE[index] andPosition:VITRI_ENEMY[index] andSelf:self] ;
        [listEnemy addObject:en];		
        SAFE_RELEASE(en);
    }
}
#pragma mark - UPDATE - TIMER
- (void)update:(ccTime)dt {
    
    for ( Enemy* eN  in listEnemy)
    {        
        if(eN!=nil)
        {                
            [eN enemyMove];
           
        }
        
    }
}
- (void)actionUpdate:(ccTime)dt {
    
    NSMutableArray *ListBullet = [[NSMutableArray alloc] init];
    for (CCSprite *bullet in listBullet) {
        CGRect bulletRect = CGRectMake(bullet.position.x - (bullet.contentSize.width/2), 
										   bullet.position.y - (bullet.contentSize.height/2), 
										   bullet.contentSize.width, 
										   bullet.contentSize.height);
        NSMutableArray *enemyDelete = [[NSMutableArray alloc] init];
         BOOL isShoot=FALSE;
        for (Enemy *iEnemy in listEnemy) {
            /// NSLog(@"++++++%d",iEnemy.health);
            CGRect iEnemyRect = CGRectMake(iEnemy.enemy.position.x - (iEnemy.enemy.contentSize.width/4), 
										   iEnemy.enemy.position.y - (iEnemy.enemy.contentSize.height/4), 
										   iEnemy.enemy.contentSize.width/2, 
										   iEnemy.enemy.contentSize.height/2);
           
			if (CGRectIntersectsRect(bulletRect, iEnemyRect)) {
               // NSLog(@"iEnemyRect %8.3f -%8.3f %8.3f %8.3f",iEnemyRect.origin.x,iEnemyRect.origin.y,iEnemyRect.size.width,iEnemyRect.size.height);
                iEnemy.health--;
                isShoot=TRUE;
                //NSLog(@"------------%d",iEnemy.health);
                if(iEnemy.health<=0)
                {
                   // NSLog(@"%d",iEnemy.health);
                    [enemyDelete addObject:iEnemy];	
                }
			}
        }
        /////////////////////////
        for (Enemy *target in enemyDelete) {
            [[SimpleAudioEngine sharedEngine] playEffect:@"Bomb_Exploding-Sound_Explorer-68256487.mp3"];
            AnimationClass *explosion=[self addImageAnimationByClass:[EXPLOSION class] withZ:10];
            explosion.position=target.enemy.position;
            id Action1 = [explosion createAnimationOneTime];
            [explosion runAction:[CCSequence actions:
                               Action1,
                               [CCCallFuncN actionWithTarget:self selector:@selector(removeExposion:)],
                               nil]];
            
            
			[listEnemy removeObject:target];
			[target.enemy removeFromParentAndCleanup:TRUE];
			//_projectilesDestroyed++;
			//if (_projectilesDestroyed >= NumberEnemy) {
				/////// Win Game
			//}
		}
		
		if (enemyDelete.count > 0||isShoot==TRUE)
        {
			[ListBullet addObject:bullet];
		}
		[enemyDelete release];
        
    }
    
    for (CCSprite *projectile in ListBullet) {
		[listBullet removeObject:projectile];
		[self removeChild:projectile cleanup:YES];
	}
	[ListBullet release];
}
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{

    
    float destX;
    BOOL shouldMove = NO;
    
    float currentX = mySHIP.position.x;
    
    if(acceleration.x > 0.01) {// 0.25  // tilting the device upwards
        
        destX = currentX - (acceleration.y * kPlayerSpeed);     
        shouldMove = YES;
       
    } else if (acceleration.x < -0.01) {  // tilting the device downwards
               
        destX = currentX + (acceleration.y * kPlayerSpeed);       
        shouldMove = YES;
        
       
    } else if(acceleration.y < -0.01) {  // tilting the device to the right
        
        destX = currentX - (acceleration.y * kPlayerSpeed);
        shouldMove = YES;
        
    } else if (acceleration.y > 0.01) {  // tilting the device to the left
        
        destX = currentX + (acceleration.y * kPlayerSpeed); 
        shouldMove = YES;
        
    } else {
        destX = currentX;
        
    }
   // NSLog(@" Acceleration.x=%8.3f acceleration.y=%8.3f  %8.3f",acceleration.x,acceleration.y,destX);
    if(shouldMove) {
        CGSize wins = [[CCDirector sharedDirector] winSize];
        // ensure we aren't moving out of bounds     
        if(destX < 30 || destX > wins.width - 30 ) {
            // do nothing
        } else {
            CCAction *action = [CCMoveTo actionWithDuration:1 position: CGPointMake(destX, mySHIP.position.y)];
            [action setTag:kHeroMovementAction];
            [mySHIP runAction:action];
        }
    } else {
        // should stop
       [mySHIP stopActionByTag:kHeroMovementAction];
    }
}
#pragma Mark -  SHOOTING START--------
-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    if(enableShooting==FALSE){return;}
    enableShooting=TRUE;
    CCSprite *bullet=[CCSprite spriteWithFile:[self getBulletByType:typeBullet]];
    bullet.position=mySHIP.position;
   [self addChild:bullet];
    [[SimpleAudioEngine sharedEngine] playEffect:@"pew-pew-lei.caf"];
    [bullet runAction:[CCSequence actions:
						   [CCMoveTo actionWithDuration:kSpeedBullet position:ccp(bullet.position.x,bullet.position.y+450)],
						   [CCCallFuncN actionWithTarget:self selector:@selector(bulletMoveFinished:)],
						   nil]];
    
    [listBullet addObject:bullet];
}
-(void)removeExposion:(id)sender
{
    AnimationClass *explosion=(AnimationClass *)sender;
    [explosion removeFromParentAndCleanup:TRUE];
}
-(void)bulletMoveFinished:(id)sender {
    
    CCSprite *sprite = (CCSprite *)sender;
	[self removeChild:sprite cleanup:YES];
    [listBullet removeObject:sprite];
}
-(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
{
    enableShooting=FALSE;
}
#pragma Mark -  SHOOTING END--------
-(NSString*)getBulletByType:(BULLET_TYPE)type
{
    switch (type) {
        case NOMARL_BULLET:
           return  @"bullet_blue.png";
            break;
        case STRONG_BULLET:
            return  @"bullet_red.png";
            break;
        case ULTIL:
            return  @"";
            break;
        default:
            return  @"";
            break;
    }
}
@end
